package com.yujistu.framework.http;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.yujistu.network.StuRestClient;
import com.yujistu.utils.CommonUtils;
import com.yujistu.utils.JsonConverter;
import com.yujistu.utils.Logger;

import java.lang.reflect.Field;
import java.util.Calendar;

import cz.msebera.android.httpclient.Header;

/**
 * Created by S3YOGA on 2015/11/3.
 */
public class YuJiHttpCenter {

    /**
     * @param context
     * @param request  网络请求，继承与BaseRequest
     * @param clz      网络返回，Result的class
     * @param listener 网络返回的回调
     * @param <Model>  Result的class
     * @param <T>      网络请求，继承与BaseRequest
     */
     public <Model, T extends BaseRequest> void startHttpRequest(Context context, T request, final Class<Model> clz, final ResultListener listener){
         int year = Calendar.getInstance().get(Calendar.YEAR);
         if(!CommonUtils.hasNetwork(context)){
             if(null != context){
                 Toast.makeText(context, "请检查网络连接", Toast.LENGTH_SHORT).show();
                 return;
             }
         }
         RequestParams params = new RequestParams();
         Logger.i("params:" + params);
         Field[]  fields = request.getClass().getDeclaredFields();
         Logger.i("fields:" + fields);
         for(Field  field : fields){
             field.setAccessible(true);
             String name = field.getName();
             String value = null;
             Logger.d("name:" + name);
             try{
                 Object object = field.get(request);
                 if(null !=object){
                     value = field.get(request).toString();
                 }else{
                   value = null;
                 }
             }catch (Exception e){
                 e.printStackTrace();
             }
             if(TextUtils.isEmpty(value))
                 continue;
             Logger.d("name:"+name+ "value:" + value);
             params.put(name, value);
         }

         if(request.getHttpType() ==  BaseRequest.HTTP_GET){
             StuRestClient.get(context, request.getHttpUrl(), params, new AsyncHttpResponseHandler(){

                 @Override
                 public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                     String jsonStr = new String(responseBody);
                     Logger.d("onSuccess:" + jsonStr);
                     try{
                         Model result = (new JsonConverter()).paresJson(jsonStr, clz);
                         listener.onSuccess(result);
                     }catch (Exception e){
                         Logger.ex(e);
                     }
                 }

                 @Override
                 public void onStart() {
                     super.onStart();
                     listener.onStart();
                     Logger.d("onStart()");
                 }

                 @Override
                 public void onFinish() {
                     super.onFinish();
                     listener.onFinish();
                     Logger.d("onFinsh()");
                 }

                 @Override
                 public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                     Logger.d("onFailure()");
                      if(null != responseBody)
                          listener.onFailed(statusCode, responseBody.toString());
                      else
                          listener.onFailed(statusCode, " ");
                 }
             });
         }else{
             StuRestClient.post(context, request.getHttpUrl(), params, new AsyncHttpResponseHandler() {

                 @Override
                 public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                     String jsonStr = new String(responseBody);
                     Logger.d("onSuccess:" + jsonStr);
                     try{
                         Model result = (new JsonConverter()).paresJson(jsonStr, clz);
                         listener.onSuccess(result);
                     }catch (Exception e){
                         Logger.ex(e);
                     }
                 }

                 @Override
                 public void onFinish() {
                     super.onFinish();
                     listener.onFinish();
                     Logger.d("onFinish()");
                 }

                 @Override
                 public void onStart() {
                     super.onStart();
                     listener.onStart();
                     Logger.d("onStart()");
                 }

                 @Override
                 public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                     Logger.d("onFailure()");
                     if(null != responseBody)
                           listener.onFailed(statusCode, responseBody.toString());
                       else
                           listener.onFailed(statusCode, " ");
                 }
             });
         }
     }

    public void closeHttpRequest(Context context){
        StuRestClient.close(context);
    }
}
